﻿using CommunityToolkit.Mvvm.Input;
using System.Threading;
using System.Threading.Tasks;
using UpperComputer.WPF.Entry.Common.Extensions;
using YFurion.Extensions;

namespace UpperComputer.WPF.Entry.Common
{
    public class OperationViewModel : BaseViewModel
    {
        /// <summary>
        /// 编号
        /// </summary>
        protected long Id { get; set; }

        /// <summary>
        /// 是否新增
        /// </summary>
        public bool IsAdd
        {
            get => Id <= 0;
        }

        private string _title;
        /// <summary>
        /// 标题
        /// </summary>
        public string Title
        {
            get
            {
                if (_title.IsNullOrWhiteSpace())
                {
                    _title = IsAdd ? Lang["新增"] : Lang["编辑"];
                }
                return _title;
            }
            set => _title = value;
        }

        public IAsyncRelayCommand<object> OkCommand { get; }

        public OperationViewModel()
        {
            OkCommand = new AsyncRelayCommand<object>(OkCommand_Execute, OkCommand_CanExecute);
        }

        protected override void CancelToken(object parameter)
        {
            base.CancelToken(parameter);
            OkCommand.CancelToken();
        }

        private bool OkCommand_CanExecute(object parameter)
        {
            return CanOk(parameter);
        }

        protected virtual bool CanOk(object parameter)
        {
            return !OkCommand.IsRunning;
        }

        private Task OkCommand_Execute(object parameter, CancellationToken cancellationToken)
        {
            return OkAsync(parameter, cancellationToken);
        }

        protected virtual Task OkAsync(object parameter, CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }
    }
}
